package com.flyfish.mytimer;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	private final static String ITEM_INDEX = "index";
	private final static String ITEM_RECORD = "record";
	private final static int STEP = 10;
	private long time = 0L; // 毫秒数
	private TextView tvDisplay;
	private boolean timerStarted = false; // 计时器是否已启动
	private boolean timerPaused=false;		//计时器是否已暂停
	private Handler mainHandler = new Handler();
	private ArrayList<HashMap<String, String>> recordList;
	private SimpleAdapter recordAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		tvDisplay = (TextView) findViewById(R.id.tvTimer);
		ListView lvRecord = (ListView) findViewById(R.id.lvRecord);
		recordList = new ArrayList<HashMap<String, String>>();
		recordAdapter = new SimpleAdapter(this, recordList, R.layout.item_record, new String[] { ITEM_INDEX,
				ITEM_RECORD }, new int[] { R.id.tvIndex, R.id.tvRecord });
		lvRecord.setAdapter(recordAdapter);
	}
	/**开始停止*/
	public void doClickSwitcher(View v) {
		if (timerStarted) {
			mainHandler.removeCallbacks(timer);
			time = 0;
		} else {
			mainHandler.postDelayed(timer, STEP);
			recordList.clear();
			recordAdapter.notifyDataSetChanged();
		}
		timerStarted = !timerStarted;
		((Button) v).setText(timerStarted ? R.string.stop : R.string.start);
	}

	private Runnable timer = new Runnable() {
		public void run() {
			time += STEP;
			tvDisplay.setText(updataDisplay());
			mainHandler.postDelayed(this, STEP);
		}
	};

	private String updataDisplay() {
		long ms = (time % 1000) / 10;
		long sec = (time % 60000) / 1000;
		long min = time / 60000;
		return (min > 9 ? "" + min : "0" + min) + ":" + (sec > 9 ? "" + sec : "0" + sec) + ":"
				+ (ms > 9 ? "" + ms : "0" + ms);
	}
	/**暂停*/
	public void doClickPause(View v){
		if(timerStarted){
			if(timerPaused){
				mainHandler.postDelayed(timer, STEP);
			}else{
				mainHandler.removeCallbacks(timer);
			}
			timerPaused=!timerPaused;
		} else {
			Toast.makeText(this, R.string.timer_not_started, Toast.LENGTH_SHORT).show();
		}
	}
	
	/** 记圈 */
	public void doClickLooper(View v) {
		if (timerStarted&&!timerPaused) {
			HashMap<String, String> item = new HashMap<String, String>();
			item.put(ITEM_INDEX, String.valueOf(recordList.size() + 1));
			item.put(ITEM_RECORD, tvDisplay.getText().toString());
			recordList.add(item);
			recordAdapter.notifyDataSetChanged();
		} else {
			Toast.makeText(this, R.string.timer_not_started, Toast.LENGTH_SHORT).show();
		}
	}

}
